import { $init, $digest } from '../../utils/common.util';
var app = getApp();
var api = require('../../api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    flowarray: ['退货', '仅退款不退货', '只退货不退款'],
    reason: ['不想要了', '货物与网上图片不符', '东西有破损', '7天无理由退货'],
    index: 0,
    dataxx:0,

    images: [],
    order_id:0,
    total_price:0,
    img_url:[],
    price:0,
    reason_str:'',
  },
  flowChange: function (e) {
    this.setData({
      index: e.detail.value
    });
  },
  myReason: function (e) {
    this.setData({
      dataxx: e.detail.value
    });
  },
  inputPrice:function(e){
    this.setData({
      price: e.detail.value
    });
  },
  inputReason:function(e){
    this.setData({
      reason_str: e.detail.value
    });
  },

  //选择图片
  onLoad(options) {
    if(options){
      if(options.order_id){
        this.setData({
          order_id: options.order_id,
          total_price:options.total_price,
        })
      }
    }
    $init(this)
  },

  chooseImage(e) {
    wx.chooseImage({
      sizeType: ['original', 'compressed'],  //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        const images = this.data.images.concat(res.tempFilePaths)
        // 限制最多只能留下3张照片
        this.data.images = images.length <= 4 ? images : images.slice(0, 4)
        $digest(this)
      }
    })
  },

  removeImage(e) {
    const idx = e.target.dataset.idx
    this.data.images.splice(idx, 1)
    $digest(this)
  },

  handleImagePreview(e) {
    const idx = e.target.dataset.idx
    const images = this.data.images
    wx.previewImage({
      current: images[idx],  //当前预览的图片
      urls: images,  //所有要预览的图片
    })
  },

  uploadImg:function (i) {
    var page =this
    wx.showLoading({
      title: '上传中',
    })
    wx.uploadFile({
      url: api.default.upload_img,
      filePath: page.data.images[i],
      name: 'image',
      complete: function (res) {
        console.log(res);
        if (res.statusCode == 200) {
          var data = JSON.parse(res.data);
          if (data.errcode == 0) {
            var img = page.data.img_url;
            img.push(data.data.url);
            page.setData({
              img_url: img
            });
            //判断图片上传完成
            console.log(i);
            if(i==page.data.images.length-1){
              console.log(page.data.images.length)
              app.request({
                url: api.shop.order_refund,
                method: 'POST',
                data: {
                  order_id: page.data.order_id,
                  reason: page.data.flowarray[page.data.index] + '\n'+ page.data.reason[page.data.dataxx] +'\n' + page.data.reason_str,
                  price:page.data.price,
                  img: page.data.img_url,
                },
                success: function (res) {
                  if (res.errcode == 0) {
                    wx.showToast({
                      title: '提交成功',
                    })
                    setTimeout(function () {
                      wx.navigateBack({
                        delta:1
                      })
                    }, 1000)
                  }
                },
                fail: function (res) {
                  wx.showModal({
                    title: '警告',
                    content: res.errmsg,
                    showCancel: false
                  })
                },
                complete: function () {
                  wx.hideLoading();
                }
              });
            }
          } else {
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }

      }
    })

  },
  submit:function(){
    var page =this
    if(page.data.price == 0){
      wx.showToast({
        title: '请输入退款金额',
        icon:'none'
      })
      return false;
    }
    if (parseFloat(page.data.price) > parseFloat(page.data.total_price)){
      wx.showToast({
        title: '退款金额不能大于可退款最大金额',
        icon: 'none'
      })
      return false;
    }
    if (page.data.images.length==0){
      wx.showToast({
        title: '请上传图片',
        icon: 'none'
      })
      return false;
    }
    for( var i=0;i<page.data.images.length;i++){
      page.uploadImg(i);
    }
  },

  submitForm(e) {
    
    const title = this.data.title
    const content = this.data.content

    if (title && content) {
      const arr = []

      //将选择的图片组成一个Promise数组，准备进行并行上传
      for (let path of this.data.images) {
        arr.push(wxUploadFile({
          url: config.urls.question + '/image/upload',
          filePath: path,
          name: 'qimg',
        }))
      }

      wx.showLoading({
        title: '正在创建...',
        mask: true
      })

      // 开始并行上传图片
      Promise.all(arr).then(res => {
        // 上传成功，获取这些图片在服务器上的地址，组成一个数组
        return res.map(item => JSON.parse(item.data).url)
      }).catch(err => {
        console.log(">>>> upload images error:", err)
      }).then(urls => {
        // 调用保存问题的后端接口
        return createQuestion({
          title: title,
          content: content,
          images: urls
        })
      }).then(res => {
        // 保存问题成功，返回上一页（通常是一个问题列表页）
        const pages = getCurrentPages();
        const currPage = pages[pages.length - 1];
        const prevPage = pages[pages.length - 2];

        // 将新创建的问题，添加到前一页（问题列表页）第一行
        prevPage.data.questions.unshift(res)
        $digest(prevPage)

        wx.navigateBack()
      }).catch(err => {
        console.log(">>>> create question error:", err)
      }).then(() => {
        wx.hideLoading()
      })
    }
  },
})